package com.manong.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.entity.SensorData;
import com.manong.service.SensorDataService;
import com.manong.service.SensorInformationService;
import com.manong.utils.Result;
import com.manong.vo.query.SensorDataQueryVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/sensorData")
public class SensorDataController {
    @Resource
    private SensorDataService sensorDataService;
    @Resource
    private SensorInformationService sensorInformationService;
    /**
     * 通过sensorId查询实时数据
     */
    @GetMapping("/getSensorDataBySensorId/{sensorId}")
    public Result getSensorDataBySensorId(@PathVariable Integer sensorId){
        SensorData sensorData = sensorDataService.findSensorDataBySensorId(sensorId);
        return Result.ok(sensorData);
    }
    /**
     * 分页查询实时数据绑定表
     */
    @GetMapping("/list")
    public Result list(SensorDataQueryVo sensorDataQueryVo){
        //创建分页对象
        IPage<SensorData> page = new Page<SensorData>(sensorDataQueryVo.getPageNo(),sensorDataQueryVo.getPageSize());
        //调用分页查询方法
        sensorDataService.findSensorDataListBySensorId(page,sensorDataQueryVo);
        //返回数据
        return Result.ok(page);
    }
    /**
     * 添加实时数据
     */
    @PostMapping("/add")
    public Result add(@RequestBody SensorData sensorData){
        if (sensorDataService.findSensorDataBySensorId(sensorData.getSensorId())!=null){
            return Result.error().message("实时数据添加失败改传感器编号已经被绑定");
        }else{
            if (sensorInformationService.findSensorInformationById(sensorData.getSensorId()).size()>0){
                if (sensorDataService.save(sensorData)){
                    return Result.ok().message("实时数据添加成功");
                }
                return Result.error().message("实时数据添加失败");
            }else {
                return Result.error().message("实时数据添加失败无传感器编号可绑定");
            }
        }
    }
    /**
     * 修改实时数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody SensorData sensorData){
        if (sensorInformationService.findSensorInformationById(sensorData.getSensorId()).size()>0){
            if (sensorDataService.updateById(sensorData)) {
                return Result.ok().message("实时数据修改成功");
            }else {
                return Result.error().message("实时数据修改失败");
            }
        }else {
            return Result.error().message("实时数据修改失败无传感器编号可绑定");
        }
    }
    /**
     * 删除实时数据
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        if (sensorDataService.removeById(id)){
            return Result.ok().message("实时数据删除成功");
        }else {
            return Result.error().message("实时数据删除失败");
        }
    }

}

